package com.wctj.api.business.common.utils;

import com.wctj.api.base.enums.ApiCode;
import com.wctj.api.base.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Slf4j
public class ValidatorUtil {
    private static final Validator VALIDATOR = Validation.byProvider(HibernateValidator.class).configure()
            .failFast(true).buildValidatorFactory().getValidator();
    /**
     * 实体校验
     *
     * @param obj 校验对象
     */
    public static <T> void validate(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(obj);
        if (constraintViolations.size() > 0) {
            ConstraintViolation<T> validateInfo = constraintViolations.iterator().next();
            // validateInfo.getMessage() 校验不通过时的信息，即message对应的值
            log.error(validateInfo.getMessage());
            throw new CustomException(ApiCode.INVALID_PARAMETER, validateInfo.getMessage());
        }
    }

}
